#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/10/4 14:12
# @Author  : leon yan
# @Site    : 
# @File    : MainWindow.py
# @Software: PyCharm
import sys
import threading

from PyQt5.QtCore import Qt, pyqtSlot, QStringListModel
from PyQt5.QtGui import QCursor, QIcon
from PyQt5.QtWidgets import QMainWindow, QApplication, QDesktopWidget, QLabel, QAbstractItemView
from loguru import logger

import Globalist as gl
import lib.alarmProcess as alarm
from About import QAbout
from AlarmList import QAlarmList
from Monitor import QMonitor
from ProductRecord import QProductRecord
from QTechnology import QTechnology
from TechnologyDetail import QTechnologyDetail
from Maintain import QMaintain
from Parameter import QParameter
from ReportLog import QReportLog
from UserLogin import QUserLogin
from lib.flex_tcp_thread_master import QPollThread as QPollThread2
from lib.flex_tcp_thread_Power import QPollThread as QPowerThread
from lib.qPlcPolling import QPlcPolling
from lib.qfileprocess import iniProcess
from lib.qpulsethread import QPollThread
from lib.qsqledit import NewAlarmLogDB
from resource.MainWindow_ui import Ui_MainWindow


def save2AlarmLog(lst):
    loginUser = gl.get_value("LoginUser")
    if loginUser:
        loginUser = gl.get_value("LoginUser")
    else:
        loginUser = ""
    for i in range(len(lst)):
        saveList = [lst[i][0], lst[i][1], lst[i][2], lst[i][3], loginUser]
        NewAlarmLogDB([saveList])


class QObjWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.setupUi(self)
        self.setWindowFlags(Qt.FramelessWindowHint)  # 无边框
        # self.showFullScreen()
        self._center()
        self._setTabFormat()
        self._buildStatusBar()

        '''Plc通信'''
        self.modBus_start_pool = []
        self._runThread()

        '''启动脉冲线程'''
        self.PulseThread = QPollThread()
        self.theThread20 = threading.Thread(target=self.PulseThread.polling_thread)
        self.theThread21 = threading.Thread(target=self.PulseThread.polling_thread2)
        self.theThread20.daemon = True
        self.theThread21.daemon = True
        self.theThread20.start()
        self.theThread21.start()
        self.PulseThread.bPulse.connect(self.do_UpdateStatus)
        gl.set_value("obj_UpdateThread", self.PulseThread)

        '''PLC 刷新'''
        self.QPlcFlashObj = QPlcPolling()
        self.thePlcThread = threading.Thread(target=self.QPlcFlashObj.plc_thread)
        self.thePlcThread.daemon = True
        self.thePlcThread.start()

        logger.info("301 系统: " + "启动中...")
        '''
        画面移动用
        '''
        self.m_flag = False
        self.m_Position = None
        ''''''
        ''''''
        self.model = QStringListModel(self)
        self.listView.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.readLogObj = iniProcess()

        logger.info("302 pyCoating system open")
        self.currentMenuName = ""
        self.on_btnMonitor_clicked()
        ''''''

    def do_UpdateStatus(self):
        """"""
        ret = alarm.rdAlarm()
        if ret:
            save2AlarmLog(ret[0])
            gl.set_value("xHasGlobalTrip", ret[1])

        if self.modBus_start_pool:
            exec(str(self.modBus_start_pool.pop(0)) + ".start()")

        """Log"""
        retList = self.readLogObj.readLogFile(r".\log\log.log")
        aa = []
        if len(retList) - 5 <= -1:
            bb = -1
        else:
            bb = len(retList) - 5
        for i in range(len(retList) - 1, bb, -1):
            aa.append(retList[i])
        self.model.setStringList(aa)
        self.listView.setModel(self.model)
        # ''''''
        # print(threading.enumerate())
        ''''''
        self.labLoginUser.setText(gl.global_var["userVar"]["LoginStatus"])

        ''''''
        if gl.get_value("xGlobalTrip"):
            self.labDeviceStatus.setText("未准备好!")
            self.labDeviceStatus.setStyleSheet("background:#ff9e66")
        else:
            self.labDeviceStatus.setText("已准备好!")
            self.labDeviceStatus.setStyleSheet("")
        ''''''

    def _center(self):
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move(int((screen.width() - size.width()) / 2),
                  int((screen.height() - size.height()) / 2 - 20))

    def _setTabFormat(self):
        self.tabWidget.setVisible(False)
        self.tabWidget.clear()  # 清除所有页面
        self.tabWidget.setTabsClosable(True)  # Page有关闭按钮
        self.tabWidget.setDocumentMode(True)
        # self.setCentralWidget(self.tabWidget)
        # self.setWindowState(Qt.WindowMaximized)  # 窗口最大化显示
        self.setAutoFillBackground(True)  # 自动绘制背景

    def _buildStatusBar(self):
        """
        构建状态栏
        """
        '''1,设备状态/2，登录状态/3，当前操作/最右侧显示通信状态'''
        self.labDeviceStatus = QLabel("", self)
        self.labDeviceStatus.setMinimumWidth(80)
        self.statusbar.addWidget(self.labDeviceStatus)

        self.LabText = QLabel("当前用户 ", self)
        self.LabText.setMinimumWidth(80)
        self.statusbar.addWidget(self.LabText)

        self.labLoginUser = QLabel("", self)
        self.labLoginUser.setMinimumWidth(100)
        self.statusbar.addWidget(self.labLoginUser)

        aa = gl.get_value('pcName') + "(" + gl.get_value("pcAddress") + ")"
        self.LabCurrentPc = QLabel(aa, self)
        self.LabCurrentPc.setMinimumWidth(300)
        self.statusbar.addWidget(self.LabCurrentPc)

        '''通信状态：在线/离线'''
        self.labSpace1 = QLabel('', self)
        self.labSpace1.setMinimumWidth(10)
        self.statusbar.addPermanentWidget(self.labSpace1)

        self.labLineStatus = QLabel(' ', self)
        self.labLineStatus.setMinimumWidth(60)
        self.labLineStatus.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.statusbar.addPermanentWidget(self.labLineStatus)
        #
        self.labLineStatus2 = QLabel(' ', self)
        self.labLineStatus2.setMinimumWidth(60)
        self.labLineStatus2.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.statusbar.addPermanentWidget(self.labLineStatus2)

        self.labLineStatus3 = QLabel("Plc", self)
        self.labLineStatus3.setMinimumWidth(40)
        self.statusbar.addPermanentWidget(self.labLineStatus3)

    def _runThread(self):
        aa = gl.global_var["deviceIpDict"]
        if aa:
            for key, value in aa.items():
                exec("self.tp_" + str(key) + "= QPollThread2('thread-" + str(value[0]) + "-" + str(key) + "')")
                exec("self.theThread_" + str(key) + " = threading.Thread(target=self.tp_" + str(key) + ".polling_thread)")
                exec("self.theThread_" + str(key) + ".daemon = True")
                self.modBus_start_pool.append("self.theThread_" + str(key))

        aa = gl.global_var["watt_hour_meter_ip"]
        if aa:
            for key, value in aa.items():
                exec("self.power_" + str(key) + "= QPowerThread('thread-" + str(key) + "-" + str(value[0]) + "-" + str(value[1]) + "')")
                exec("self.powerThread_" + str(key) + " = threading.Thread(target=self.power_" + str(
                    key) + ".polling_thread)")
                exec("self.powerThread_" + str(key) + ".daemon = True")
                self.modBus_start_pool.append("self.powerThread_" + str(key))

    '''
    按钮菜单切换
    '''

    def _showBtnInfo(self, btn):
        # print(btn)
        self.widgetMonitor.setStyleSheet('')
        self.widget.setStyleSheet('')
        self.widgetRecord.setStyleSheet('')
        self.widgetProductData.setStyleSheet('')
        self.widgetMaintain.setStyleSheet('')
        self.widgetSystem.setStyleSheet('')
        self.widgetLog.setStyleSheet('')

    @pyqtSlot()
    def on_btnMonitor_clicked(self):
        if self.currentMenuName == "btnMonitor":
            return
        if self.tabWidget.currentIndex() >= 0:
            aForm = self.tabWidget.widget(self.tabWidget.currentIndex())
            aForm.close()
        self._showBtnInfo(self.sender())
        self.widgetMonitor.setStyleSheet('background-color: rgb(255, 255, 255);')
        self.tabWidget.clear()  # 清除所有页面
        formDoc = QMonitor()
        formDoc.setAttribute(Qt.WA_DeleteOnClose)  # 关闭时自动删除
        title = ""
        curIndex = self.tabWidget.addTab(formDoc, title)  # 添加到tabWidget
        self.tabWidget.setCurrentIndex(curIndex)
        self.tabWidget.setVisible(True)
        self.currentMenuName = "btnMonitor"

    @pyqtSlot()
    def on_btnRecord_clicked(self):
        if self.currentMenuName == "btnRecord":
            return
        if self.tabWidget.currentIndex() >= 0:
            aForm = self.tabWidget.widget(self.tabWidget.currentIndex())
            aForm.close()
        self._showBtnInfo(self.sender())
        self.widgetRecord.setStyleSheet('background-color: rgb(255, 255, 255);')
        self.tabWidget.clear()  # 清除所有页面
        formDoc = QProductRecord()
        formDoc.setAttribute(Qt.WA_DeleteOnClose)  # 关闭时自动删除
        title = ""
        curIndex = self.tabWidget.addTab(formDoc, title)  # 添加到tabWidget
        self.tabWidget.setCurrentIndex(curIndex)
        self.tabWidget.setVisible(True)
        self.currentMenuName = "btnRecord"

    @pyqtSlot()
    def on_btnProductData_clicked(self):
        # if self.currentMenuName == "btnProductData":
        #     return
        # if self.tabWidget.currentIndex() >= 0:
        #     aForm = self.tabWidget.widget(self.tabWidget.currentIndex())
        #     aForm.close()
        self._showBtnInfo(self.sender())
        self.widgetProductData.setStyleSheet('background-color: rgb(255, 255, 255);')
        self.tabWidget.clear()  # 清除所有页面
        formDoc = QTechnology()
        formDoc.setAttribute(Qt.WA_DeleteOnClose)  # 关闭时自动删除
        title = ""
        curIndex = self.tabWidget.addTab(formDoc, title)  # 添加到tabWidget
        self.tabWidget.setCurrentIndex(curIndex)
        self.tabWidget.setVisible(True)
        self.currentMenuName = "btnProductData"
        formDoc.bOpenDetailData.connect(self.doOpenDetailData)

    @pyqtSlot()
    def doOpenDetailData(self):
        # if self.currentMenuName != "btnProductData":
        #     return
        # if self.tabWidget.currentIndex() >= 0:
        #     aForm = self.tabWidget.widget(self.tabWidget.currentIndex())
        #     aForm.close()
        self._showBtnInfo(self.sender())
        self.widgetProductData.setStyleSheet('background-color: rgb(255, 255, 255);')
        self.tabWidget.clear()  # 清除所有页面
        formDoc = QTechnologyDetail()
        formDoc.setAttribute(Qt.WA_DeleteOnClose)  # 关闭时自动删除
        title = ""
        curIndex = self.tabWidget.addTab(formDoc, title)  # 添加到tabWidget
        self.tabWidget.setCurrentIndex(curIndex)
        self.tabWidget.setVisible(True)
        self.currentMenuName = "btnProductData"
        formDoc.bCloseDetailData.connect(self.on_btnProductData_clicked)

    @pyqtSlot()
    def on_btnMaintain_clicked(self):
        if self.currentMenuName == "btnMaintain":
            return
        if self.tabWidget.currentIndex() >= 0:
            aForm = self.tabWidget.widget(self.tabWidget.currentIndex())
            aForm.close()
        self._showBtnInfo(self.sender())
        self.widgetMaintain.setStyleSheet('background-color: rgb(255, 255, 255);')
        self.tabWidget.clear()  # 清除所有页面
        formDoc = QMaintain()
        formDoc.setAttribute(Qt.WA_DeleteOnClose)  # 关闭时自动删除
        title = ""
        curIndex = self.tabWidget.addTab(formDoc, title)  # 添加到tabWidget
        self.tabWidget.setCurrentIndex(curIndex)
        self.tabWidget.setVisible(True)
        self.currentMenuName = "btnMaintain"

    @pyqtSlot()
    def on_btnViewAlarm_clicked(self):
        if self.currentMenuName == "btnViewAlarm":
            return
        if self.tabWidget.currentIndex() >= 0:
            aForm = self.tabWidget.widget(self.tabWidget.currentIndex())
            aForm.close()
        self._showBtnInfo(self.sender())
        self.widget.setStyleSheet('background-color: rgb(255, 255, 255);')
        self.tabWidget.clear()  # 清除所有页面
        formDoc = QAlarmList()
        formDoc.setAttribute(Qt.WA_DeleteOnClose)  # 关闭时自动删除
        title = ""
        curIndex = self.tabWidget.addTab(formDoc, title)  # 添加到tabWidget
        self.tabWidget.setCurrentIndex(curIndex)
        self.tabWidget.setVisible(True)
        self.currentMenuName = "btnViewAlarm"

    '''数据设定***************************************'''

    @pyqtSlot()
    def on_btnSystem_clicked(self):
        if self.currentMenuName == "btnSystem":
            return
        if gl.global_var["userVar"]["LoginUser"] != '':
            self.do_OpenParameter()
        else:
            self.do_login()

    @pyqtSlot()
    def on_btnLog_clicked(self):
        if self.currentMenuName == "btnLog":
            return
        if self.tabWidget.currentIndex() >= 0:
            aForm = self.tabWidget.widget(self.tabWidget.currentIndex())
            aForm.close()
        self._showBtnInfo(self.sender())
        self.widgetLog.setStyleSheet('background-color: rgb(255, 255, 255);')
        self.tabWidget.clear()  # 清除所有页面
        formDoc = QReportLog()
        formDoc.setAttribute(Qt.WA_DeleteOnClose)  # 关闭时自动删除
        title = ""
        curIndex = self.tabWidget.addTab(formDoc, title)  # 添加到tabWidget
        self.tabWidget.setCurrentIndex(curIndex)
        self.tabWidget.setVisible(True)
        self.currentMenuName = "btnLog"

    '''软件--关于部分'''

    @pyqtSlot()
    def on_btnAbout_clicked(self):
        formDoc = QAbout(self)  # 必须传递self，否则无法显示
        formDoc.setAttribute(Qt.WA_DeleteOnClose)
        formDoc.setWindowFlag(Qt.Window, True)

        formDoc.setWindowModality(Qt.WindowModal)
        formDoc.setWindowFlag(Qt.CustomizeWindowHint, True)
        formDoc.setWindowFlag(Qt.WindowMinMaxButtonsHint, False)
        formDoc.setWindowFlag(Qt.WindowCloseButtonHint, True)
        formDoc.setWindowFlag(Qt.WindowContextHelpButtonHint, False)
        formDoc.setWindowFlag(Qt.WindowStaysOnTopHint, True)

        formDoc.setWindowOpacity(1.0)  # 窗口透明度
        formDoc.show()

    '''exit***************************************'''

    @pyqtSlot()
    def on_btnExit_clicked(self):
        self.close()

    '''login***************************************'''

    def do_login(self):
        formDoc = QUserLogin(self)  # 必须传递self，否则无法显示
        formDoc.setAttribute(Qt.WA_DeleteOnClose)
        formDoc.setWindowFlag(Qt.Window, True)

        formDoc.setWindowModality(Qt.WindowModal)
        formDoc.setWindowFlag(Qt.CustomizeWindowHint, True)
        formDoc.setWindowFlag(Qt.WindowMinMaxButtonsHint, False)
        formDoc.setWindowFlag(Qt.WindowCloseButtonHint, True)
        formDoc.setWindowFlag(Qt.WindowStaysOnTopHint, True)

        formDoc.setWindowOpacity(1.0)  # 窗口透明度
        formDoc.show()
        formDoc.LoginIsOk.connect(self.do_OpenParameter)
        formDoc.LoginIsNg.connect(self.on_btnMonitor_clicked)

    def do_OpenParameter(self):
        if self.tabWidget.currentIndex() >= 0:
            aForm = self.tabWidget.widget(self.tabWidget.currentIndex())
            aForm.close()
        self._showBtnInfo(self.sender())
        self.widgetSystem.setStyleSheet('background-color: rgb(255, 255, 255);')
        self.tabWidget.clear()  # 清除所有页面
        formDoc = QParameter()
        formDoc.setAttribute(Qt.WA_DeleteOnClose)  # 关闭时自动删除
        title = ""
        curIndex = self.tabWidget.addTab(formDoc, title)  # 添加到tabWidget
        self.tabWidget.setCurrentIndex(curIndex)
        self.tabWidget.setVisible(True)
        ''''''
        formDoc.LoginIsOut.connect(self.on_btnMonitor_clicked)
        self.currentMenuName = "btnSystem"
        ''''''

    '''
    ********************************************************************************
    '''

    def mouseDoubleClickEvent(self, event):
        aa = (event.globalPos() - self.pos())
        eActXPos = aa.x()
        eActYPos = aa.y()
        eXMinPos = self.topframe.pos().x()
        eXMaxPos = self.topframe.pos().x() + self.topframe.width()
        eYMinPos = self.topframe.pos().y()
        eYMaxPos = self.topframe.pos().y() + self.topframe.height()
        bOk1 = eXMinPos < eActXPos < eXMaxPos
        bOk2 = eYMinPos < eActYPos < eYMaxPos
        if event.button() == Qt.LeftButton and bOk1 and bOk2:
            self.on_btnMax_clicked()

    @pyqtSlot()
    def on_btnMin_clicked(self):
        self.showMinimized()

    @pyqtSlot()
    def on_btnMax_clicked(self):
        if self.isMaximized():
            self.showNormal()
            self.btnMax.setIcon(QIcon("./resource/icons/max1-1.png"))
        else:
            self.showMaximized()
            self.btnMax.setIcon(QIcon("./resource/icons/max2-1.png"))

    @pyqtSlot()
    def on_btnClose_clicked(self):
        self.close()

    def mousePressEvent(self, event):
        if self.isMaximized():
            return
        aa = (event.globalPos() - self.pos())
        eActXPos = aa.x()
        eActYPos = aa.y()
        eXMinPos = self.topframe.pos().x()
        eXMaxPos = self.topframe.pos().x() + self.topframe.width()
        eYMinPos = self.topframe.pos().y()
        eYMaxPos = self.topframe.pos().y() + self.topframe.height()
        bOk1 = eXMinPos < eActXPos < eXMaxPos
        bOk2 = eYMinPos < eActYPos < eYMaxPos
        if event.button() == Qt.LeftButton and bOk1 and bOk2:
            self.m_flag = True
            self.m_Position = event.globalPos() - self.pos()  # 获取鼠标相对窗口的位置
            event.accept()
            # self.setCursor(QCursor(Qt.OpenHandCursor))  # 更改鼠标图标

    def mouseMoveEvent(self, QMouseEvent):
        if Qt.LeftButton and self.m_flag:
            self.move(QMouseEvent.globalPos() - self.m_Position)  # 更改窗口位置
            QMouseEvent.accept()

    def mouseReleaseEvent(self, QMouseEvent):
        self.m_flag = False
        self.setCursor(QCursor(Qt.ArrowCursor))

    def __del__(self):
        print("MainWindow is deleted")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    windowObj = QObjWindow()
    windowObj.show()
    sys.exit(app.exec_())
